# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : running_trend_view.py
# Time       ：2023/11/2 17:01
# Author     ：YangYong
# version    ：python 3.10
# Description：流程运行趋势
"""
from datetime import datetime, timedelta

from flask_restx import Resource, fields
from sqlalchemy import extract, func

from apis.data_screen import data_screen_ns
from apis.data_screen.schema.running_trend_schema import RunningTrendSchema
from apis.orderlines.models import ProcessInstance
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel


class RunningTrendView(Resource):
    url = '/run_trend'

    def __init__(self, *args, **kwargs):
        super(RunningTrendView, self).__init__(*args, **kwargs)
        self.current_data = f"{datetime.now().strftime('%Y-%m-%d')} 23.59.59"
        self.current_month = f"{(datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')} 23.59.59"

    @handle_api_error()
    @data_screen_ns.doc(description='流程运行趋势')
    def get(self):
        """流程运行趋势"""
        objs = db.session.query(
            func.concat(
                extract('month', ProcessInstance.start_time),
                '-',
                extract('day', ProcessInstance.start_time),
            ).label('date'),
            func.count(1).label('value')
        ).filter(
            ProcessInstance.start_time.between(self.current_month, self.current_data)
        ).group_by('date').all()
        info = RunningTrendSchema().dump(objs, many=True)
        dates = list()
        value = list()
        for item in info:
            dates.append(item.get('date'))
            value.append(item.get('value'))
        response_data = {'data': dates, 'value': value, 'unit': ['运行次数']}
        return generate_response(response_data)
